import React, { FC, ReactElement } from 'react'
import { Layout, Menu, Dropdown, Row, Col } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import { Link, useHistory } from 'react-router-dom'
import { observer } from 'mobx-react'
import headImg from '@/assets/images/logo.svg'
import { useStore } from '@/store'
import setRouter from '@/routes'
import getMenuTree from '@/hooks/menu'

import './index.scss'

const { Header } = Layout

type Props = {
  token?: string
}

const AppHeader: FC<Props> = () => {
  const { userStore, appStore } = useStore()
  const history = useHistory()
  const openKey: Array<string> = []
  const openMenu: Array<string> = []

  const asyncRoutes = setRouter(userStore.menu)
  const menuTree: ReactElement[] = getMenuTree(asyncRoutes)
  menuTree.unshift(<Menu.Item key="logo"><Link to="/"><img src={headImg} alt="logo" className="logo" /></Link></Menu.Item>)

  const onDropMenu = (e: any) => {
    if (e.key === 'logout') {
      userStore.logout()
      history.push('/login')
    }
  }
  const rightMenu = (
    <Menu onClick={onDropMenu}>
      <Menu.Divider />
      <Menu.Item key="logout">退出登录</Menu.Item>
    </Menu>
  )
  return (
    <Header className={`app-header ${appStore.headerHide ? 'hide' : ''}`}>
      <Row>
        <Col span={20}>
          <Menu theme="dark" mode="horizontal" selectedKeys={openKey} defaultOpenKeys={openMenu}>
            {menuTree}
          </Menu>
        </Col>
        <Col span={4}>
          <Dropdown className="right-top-me" overlay={rightMenu}>
            <span className="ant-dropdown-link">
              {userStore.userInfo?.nickName} <DownOutlined />
            </span>
          </Dropdown>
        </Col>
      </Row>
    </Header>
  )
}

export default observer(AppHeader)
